/**
 * 购物车抛物线动画
 * @param {HTMLElement} eleBtn 加入购物车按钮
 * @param {HTMLElement} eleCart 购物车元素
 * @param {HTMLDivElement} eleFlyItem 执行动画的元素，一般是一个包裹图片的div
 */
export function parabolic(eleBtn, eleCart, eleFlyItem) {
  let isRunning = false,
    timer = null;
  const eleFlyImg = eleFlyItem.querySelector("img");
  const eleNum = eleCart.querySelector(".num");
  if (!eleNum) {
    eleCart.innerHTML += '<span class="num">0</span>';
  }
  eleBtn.addEventListener("click", function () {
    const boundBtn = eleBtn.getBoundingClientRect();
    const boundCart = eleCart.getBoundingClientRect();
    const offsetX =
      boundCart.left +
      boundCart.width / 2 -
      (boundBtn.left + boundBtn.width / 2);
    const offsetY =
      boundCart.top + boundCart / 2 - (boundBtn.top + boundBtn.height / 2);
    const scrollTop =
      document.documentElement.scrollTop || document.body.scrollTop || 0;
    const scrollLeft =
      document.documentElement.scrollLeft || document.body.scrollLeft || 0;
    if (isRunning) return;
    timer && clearTimeout(timer);
    eleFlyItem.style.display = "block";
    eleFlyItem.style.left = `${
      boundBtn.left + scrollLeft + this.clientWidth / 2
    }px`;
    eleFlyItem.style.top = `${
      boundBtn.top + scrollTop + this.clientHeight / 2
    }px`;
    eleFlyItem.style.transform = "translateX(" + offsetX + "px)";
    eleFlyImg.style.transform = "translateY(" + offsetY + "px)";
    isRunning = true;
    timer = setTimeout(() => {
      eleFlyItem.style.display = "none";
      eleFlyItem.style.transform = "translateX(0px)";
      eleFlyImg.style.transform = "translateY(0px)";
      eleNum.innerText = +eleNum.innerText + 1;
      isRunning = false;
    }, 400);
  });
}
